package edu.upf.opencities.web.connector.impl;

import java.io.DataOutputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

import org.apache.axiom.om.util.Base64;
import org.apache.log4j.Logger;



import edu.upf.opencities.datamodel.User;
import edu.upf.opencities.web.connector.Connector;

public class ConnectorImpl implements Connector {

	private static ConnectorImpl connector = null;
	public static Logger logger = Logger.getLogger(ConnectorImpl.class);

	public static synchronized ConnectorImpl getInstace() {
		if (null == connector) {
			connector = new ConnectorImpl();
		}
		return connector;
	}

	public boolean send(String command, Object object, String objectType,
			User user, String type) {
			
		HttpURLConnection connection = null;
		try{
		URL url = new URL(command);
		connection =  (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("POST");
		}catch (Exception e) {}
		
        connection.setDoInput(true);
        connection.setDoOutput(true);
        String authorizationHeader = Base64.encode((user.getEmail() + ":" + user.getPassword()).getBytes());
        System.out.println("Auth "+authorizationHeader);
        connection.setRequestProperty("Authorization", "Basic " + authorizationHeader);
        connection.setRequestProperty("Content-Type", "application/xml;charset=UTF-8");
		
	

        int status = 0;
		Writer writer = new StringWriter();
		try {
			JAXBContext jbc = JAXBContext
					.newInstance("edu.upf.opencities.datamodel");
			Marshaller m = jbc.createMarshaller();
			m.marshal(object, writer);
			System.out.println("STRING"+writer.toString());
			System.out.println("COMMAND "+command);

		} catch (Exception e) {	}
		
		try {
            DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
            wr.write (writer.toString().getBytes());
            wr.flush ();
            wr.close ();
            status = connection.getResponseCode();
            System.out.println("STATUS: "+status);
		}catch (Exception e) {}

		if (200 == status) {
			return true;
		} else {
			return false;
		}
	}
}
